import { ref, computed, onMounted, watch } from "vue";
import { defineStore } from "pinia";
import { getWeather, getNowWeather } from "@/apis/weather";
// 定义counter空间
export const useCityListStore = defineStore("cityList", () => {
  const cityList = ref([]);
  const showCity = ref("");
  const showCityWeather = ref("");
  // 设置要显示的城市信息，并获取该城市的天气数据
  const setShowCity = (name, adcode) => {
    let weather = "";
    getNowWeather(adcode).then((res) => {
      weather = res.data.lives[0];
      console.log(weather);
      showCity.value = { adcode, name, weather };
    });
    getWeather(adcode).then((res) => {
      showCityWeather.value = res.data.forecasts[0].casts;
      console.log(showCityWeather.value);
    });
  };
  // 将当前显示的城市添加到城市列表中
  const addCityList = () => {
    cityList.value.push(showCity.value);
  };
  // 从城市列表中移除指定adcode的城市
  const removeCityList = (adcode) => {
    cityList.value = cityList.value.filter((item) => item.adcode !== adcode);
    console.log(cityList.value);
  };
  // 更新城市列表，并获取每个城市的最新天气数据
  const updateCityList = (list) => {
    list.forEach((item) => {
      getNowWeather(item.adcode).then((res) => {
        item.weather = res.data.lives[0];
        console.log(item.weather);
      });
    });
    cityList.value = list;
  };
  // 获取指定adcode城市的天气数据
  const getCityWeather = (adcode) => {
    getWeather(adcode).then((res) => {
      showCityWeather.value = res.data.forecasts[0].casts;
      console.log(showCityWeather.value);
    });
  };
  // 监听cityList变化，将其存储到localStorage
  watch(
    cityList,
    () => {
      //console.log('cityList变化了', cityList.value)
      localStorage.setItem("arr", JSON.stringify(cityList.value));
    },
    { deep: true }
  );
  // 页面加载完成后，从localStorage中获取数据
  onMounted(() => {
    if (localStorage.getItem("arr")) {
      //console.log('localStorage中有数据', localStorage.getItem('arr'))
      const arr = JSON.parse(localStorage.getItem("arr"));
      cityList.value = arr;
    }
    updateCityList(cityList.value);
  });
  return {
    cityList,
    showCity,
    showCityWeather,
    getCityWeather,
    addCityList,
    setShowCity,
    removeCityList,
  };
});
